package cn.acrdpm.tools;

import cn.acrdpm.entity.Mail;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 *  邮箱验证工具类
 * @author 张敏
 * @date 2021/3/8
 */
public class EmailUtil {

    /**
     * 用户邮箱验证码获取
     * @param mail：邮件
     * @return
     * @throws EmailException
     */
    public static Boolean sendEmail(Mail mail) throws EmailException {

        //创建htmlemail实例
        HtmlEmail email=new HtmlEmail();
        //设置邮箱的SMTP服务器主机名:此处需要进行邮箱的类型判断设置不同的服务
        email.setHostName("smtp.qq.com");

     /*   if(formEmail.contains("@163.com")){
            email.setHostName("smtp.163.com");
        }
        if(formEmail.contains("@123.com")){
            email.setHostName("smtp.123.com");
        }*/

        //设置发送的字符集类型
        email.setCharset("utf-8");
        //设置收件人地址
        email.addTo(mail.getTo());
        //发送人的邮箱和用户名
        email.setFrom("acrdpm@qq.com","肌肉码农");
        //设置邮箱地址和授权码
        email.setAuthentication("acrdpm@qq.com", "irhiqrmhfhgrjgge");
        //设置发送邮件主题
        email.setSubject(mail.getTitle());
        //设置发送邮件内容
        String code=randomNum(6);
        email.setMsg(mail.getContent() + code);
        //发送邮件
        String send = email.send();
        if (!ObjectUtils.isEmpty(send)){
            return true;
        }
        return  false;
    }

    //生成6位随机数字
    public static String randomNum(int index){
        String number="0123456789";
        Random random=new Random();
        StringBuffer buffer=new StringBuffer();
        for (int i = 0; i <index; i++) {
            //设置随机数
            int num = random.nextInt(number.length() - 1);
            String substring = number.substring(num,num+1);
            buffer.append(substring);
        }
        return buffer.toString();

    }

    // 随机验证码
    public String achieveCode() {
        //由于数字 1 、 0 和字母 O 、l 有时分不清楚，所以，没有数字 1 、 0
        String[] beforeShuffle= new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
                "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
                "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z" };
        List list = Arrays.asList(beforeShuffle);//将数组转换为集合
        Collections.shuffle(list);  //打乱集合顺序
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(list.get(i)); //将集合转化为字符串
        }
        Random random=new Random();
        int randNum=random.nextInt(list.size()-7);
        return sb.substring(randNum,randNum+6);  //随机生成6位验证码
    }
}
